//
//  SettingViewController.m
//  ksjv2
//
//  Created by mac on 14/12/16.
//  Copyright (c) 2014年 CnbizMedia. All rights reserved.
//
//---------------------------------------------------------
//                    *              *
//                  *      设置界面     *
//                    *              *
//---------------------------------------------------------
#import "SettingViewController.h"
#import "Util.h"
#import "OpinionViewController.h"
#import "LoginViewController.h"
#import "FontTableViewController.h"


@interface SettingViewController ()<SKProductsRequestDelegate,SKRequestDelegate,SKPaymentTransactionObserver>
{

}
@end

@implementation SettingViewController
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    if(error){
        [SVProgressHUD showErrorWithStatus:error.userInfo[@"NSLocalizedDescription"]];
    }
}

- (void)requestDidFinish:(SKRequest *)request{
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
    NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    if(encodeStr != nil){
        [self verifyTransaction];
        return;
    }
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}

-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    for (SKProduct *op in response.products) {
        NSLog(@"%@",op.description);
    }
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"设置";
    self.tableView.backgroundColor=UIColorFromRGB(0xf5f5f5);
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    UIButton *buttonf=[UIButton buttonWithType:UIButtonTypeCustom];
    [buttonf setFrame:CGRectMake(0, 0, 22, 22)];
    [buttonf addTarget:self action:@selector(popOfDismss) forControlEvents:UIControlEventTouchUpInside];
    [buttonf setImage:[UIImage imageNamed:@"dismiss"] forState:UIControlStateNormal];
    
    NSString *newOldYear = [UserDefaults objectForKey:@"NewYear" ];
    if ([newOldYear isEqualToString:@"NewYear"]) {
        //状态栏的文字颜色换成白色
        //        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        
        //            [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
        [buttonf setImage:[UIImage imageNamed:@"dismissGray"] forState:UIControlStateNormal];
        
    }
     UIBarButtonItem*leftBarItem = [[UIBarButtonItem alloc]initWithCustomView:buttonf];
    self.navigationItem.leftBarButtonItem=leftBarItem;

}

-(void)popOfDismss{
    if ([[self.navigationController viewControllers] count]>=2) {
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section==0) {
        return 1;
    }else if (section==1){
        return 1;
    }else if (section==2){
        return 4;
    }else{
        return 0;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 45;

}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView*view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 10)];
    view.backgroundColor=UIColorFromRGB(0xf5f5f5);

    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"setcell" forIndexPath:indexPath];
    if (cell==nil) {
        cell=[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"setcell"];
        
    }
    
    UILabel*label=(UILabel*)[cell.contentView viewWithTag:22];
    
    if (indexPath.section==0){
       
           label.text=@"恢复购买";
        cell.accessoryType=UITableViewCellAccessoryNone;
        
        
    }else if (indexPath.section==1){
        cell.accessoryType=UITableViewCellAccessoryNone;
        float tmpSize = [[SDImageCache sharedImageCache] getSize];
        
        NSString *clearCacheName =[NSString stringWithFormat:@"清理緩存(%.2fM)",tmpSize/1024/1024];
        label.text=[NSString stringWithFormat:@"%@",clearCacheName];
    }else if (indexPath.section==2){
        if (indexPath.row==0) {
            label.text=@"字体大小";
        }else if (indexPath.row==1) {
            label.text=@"给看商界提意见";
        }else if (indexPath.row==2){
            label.text=@"评价看商界";
        }else if (indexPath.row==3){
            label.text=@"关于";
        }
    }
    
    return cell;
}
- (void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error{
    NSLog(@"restoreCompletedTransactionsFailedWithError:%@",error);
    [SVProgressHUD dismiss];
    NSString *msg = [NSString stringWithFormat:@"商品恢复失败:%@",error];
    if(error.code == SKErrorPaymentCancelled) {
        msg = @"用户已取消恢复。";
    }
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}

-(void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue{
    NSLog(@"Restore:%@",queue.transactions);
    //[self verifyTransaction];
    if(queue.transactions.count == 0){
        
        [SVProgressHUD showErrorWithStatus:@"没有可恢复的数据。"];
        return;
    }
    //[SVProgressHUD showWithStatus:[NSString stringWithFormat:@"开始验证订单信息..1/%d",count] maskType:SVProgressHUDMaskTypeGradient];
}
//BOOL isRestored = NO;
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0){
        if (IFUserLogin) {
            if(![SKPaymentQueue canMakePayments]){
                SHOW_ALERT(@"无法使用内购", @"您已关闭内购功能，请开启内购功能后再尝试次操作。");
                return;
            }
            SKReceiptRefreshRequest *req = [[SKReceiptRefreshRequest alloc]init];
            [req setDelegate:self];
            [req start];
            [SVProgressHUD showWithStatus:@"正在获取订单信息..." maskType:SVProgressHUDMaskTypeGradient];
            return;
    
            NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
            NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
            NSString *encodingStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
            NSMutableDictionary *mag_Info = [[NSMutableDictionary alloc]init];
            [mag_Info setObject:encodingStr forKey:@"data"];
            [[AppAPIClient sharedClient] POST:@"Magazine/Subscribe"
                                   parameters:mag_Info
                                      success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                          int code = [responseObject[@"code"] intValue];
                                          if(code == 1){
                                              [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"恢复成功.共计: %@ 条记录.",responseObject[@"data"]]];
                                              NSString *alertMsg = [NSString stringWithFormat:@"恢复成功.共计:%@条记录.",responseObject[@"data"]];
                                              SHOW_ALERT(@"提示", alertMsg);
                                          }else{
                                              [SVProgressHUD dismiss];
                                              SHOW_ALERT(@"提示", @"购买恢复失败,订单创建用户与当前用户不符合。请联系客服人员进行处理。");
                                          }
                                          
                                          NSLog(@"%@",responseObject);
                                      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                          NSLog(@"%@",operation.responseString);
                                          [SVProgressHUD showErrorWithStatus:@"恢复出现错误.请重试."];
                                      }];
            }else{
            UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
            LoginViewController*login=[story instantiateViewControllerWithIdentifier:@"LoginViewController"];
            [self.navigationController pushViewController:login animated:YES];
            }

    }else if (indexPath.section==1){
        [[SDImageCache sharedImageCache] clearDisk];
        
        [[SDImageCache sharedImageCache] clearMemory];

        [tableView reloadData];
//        @"清理缓存";
    }else if (indexPath.section==2){
        if (indexPath.row==0) {
            FontTableViewController*font=[[FontTableViewController alloc]init];
            font.view.backgroundColor=[UIColor whiteColor];
            font.title=@"字体大小设置";
            [self.navigationController pushViewController:font animated:YES];
            
        }else if (indexPath.row==1) {
            [self performSegueWithIdentifier:@"pushProblemView" sender:self];// setPopinion
//            @"给看商界提意见";
        }else if (indexPath.row==2){
            // 评分
            NSString *str = [NSString stringWithFormat:@"%@",[[[[[NSUserDefaults standardUserDefaults] objectForKey:@"ad"] objectForKey:@"data"] objectForKey:@"app"] objectForKey:@"url"]];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        }else if (indexPath.row==3){
            [self performSegueWithIdentifier:@"setPabout" sender:self];
//            @"关于";
        }
    }
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

//    UIViewController *destination = segue.destinationViewController;
//    if([destination isKindOfClass:[OpinionViewController class]]){
//        [destination setValue:@"set" forKey:@"Source"];
//    }
}
- (BOOL)verifyTransaction{
    
    //[SVProgressHUD showWithStatus: maskType:SVProgressHUDMaskTypeGradient];
    [SVProgressHUD showWithStatus:@"正在验证订单.." maskType:SVProgressHUDMaskTypeGradient];
    //NSLog(@"%@",transaction.transactionIdentifier);
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
    NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    
    if(encodeStr == nil){
        encodeStr = @"";
    }
    //NSString *test = [NSString stringWithContentsOfURL:receiptURL encoding:NSUTF8StringEncoding error:nil];
    //NSString *payload = [ NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}",encodeStr];
    //[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
//    ,@"debug":@"1"
    [[AppAPIClient sharedClient] POST:@"Magazine/Restore" parameters:@{@"id":@"1",@"data":encodeStr} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //[SVProgressHUD showWithStatus:@"正在验证订单.." maskType:SVProgressHUDMaskTypeGradient];
        if([responseObject[@"code"] intValue] == 1){
            [SVProgressHUD dismiss];
            NSString *alertMsg = [NSString stringWithFormat:@"恢复成功.共计:%@条记录.",responseObject[@"data"]];
            SHOW_ALERT(@"提示", alertMsg);
        }else{
            //SHOW_ALERT(@"恢复提示", @"恢复失败，请尝试恢复购买。");
            [SVProgressHUD showErrorWithStatus:@"恢复失败，请尝试恢复购买。"];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD dismiss];
        SHOW_ALERT(@"恢复提示", @"恢复失败，请重试。");
    }];
    
    return NO;
}
- (void)paymentQueue:(SKPaymentQueue *)queue removedTransactions:(NSArray *)transactions{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
    
    for(SKPaymentTransaction *t in transactions){
        
        [[SKPaymentQueue defaultQueue] finishTransaction:t];
        switch (t.transactionState) {
            case SKPaymentTransactionStatePurchased:
                
                
                //[[SKPaymentQueue defaultQueue] finishTransaction:t];
                break;
            case SKPaymentTransactionStateFailed:{
                NSString *reason = @"";
                if(t.error.code == SKErrorPaymentCancelled){
                    reason = @"用户取消交易。";
                }else if(t.error.code == SKErrorPaymentInvalid){
                    reason = @"无效支付数据。";
                }else if(t.error.code == SKErrorPaymentNotAllowed){
                    reason = @"用户不允许购买。";
                }
                reason = [NSString stringWithFormat:@"订单:%@ 失败,%@",t.transactionIdentifier,reason];
                //[[SKPaymentQueue defaultQueue] finishTransaction:t];
                [SVProgressHUD dismiss];
                SHOW_ALERT(@"购买失败", reason);
                break;
            }
            case SKPaymentTransactionStateRestored:
                [[SKPaymentQueue defaultQueue] finishTransaction:t];
                break;
            case SKPaymentTransactionStatePurchasing:
                [SVProgressHUD showWithStatus:@"正在准备支付..." maskType:SVProgressHUDMaskTypeGradient];
                break;
            default:
                
                break;
        }
    }
    [self verifyTransaction];
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

@end
